<template>
  <el-dialog v-model="props.visible" title="支付订单" width="700px" :before-close="handleClose">
    <!-- 订单信息 -->
    <el-card shadow="never" style="margin-bottom: 20px">
      <div style="display: flex; justify-content: space-between">
        <div>
          <h3 style="margin: 0 0 10px 0">订单号: {{ orderData.id }}</h3>
          <p style="margin: 5px 0; color: #666">
            创建时间: {{ formatDateTime(orderData.createTime) }}
          </p>
          <p style="margin: 5px 0; color: #666">
            订单状态: {{ getOrderStatusText(orderData.orderStatus) }}
          </p>
          <p style="margin: 5px 0; color: #666">
            支付状态: {{ getPayStatusText(orderData.payStatus) }}
          </p>
          <p style="margin: 5px 0; color: #666">
            收货人: {{ orderData.receiverName }} {{ orderData.receiverPhone }}
          </p>
          <p style="margin: 5px 0; color: #666">
            收货地址: {{ orderData.address }}
          </p>
        </div>
        <div style="text-align: right">
          <p style="margin: 5px 0; font-size: 24px; color: #f56c6c">
            ￥{{ orderData.paymentAmount?.toFixed(2) }}
          </p>
          <p style="margin: 5px 0; color: #666">数量: {{ orderData.buyNumber }}</p>
          <p style="margin: 5px 0; color: #666">支付剩余时间: {{ countdown }}</p>
        </div>
      </div>
    </el-card>

    <!-- 支付方式 -->
<!--    <div v-if="orderData.payStatus === 0" style="margin-bottom: 20px">-->
<!--      <h3 style="margin: 0 0 15px 0">选择支付方式</h3>-->
<!--      <el-radio-group v-model="paymentMethod" style="width: 100%">-->
<!--        <el-card-->
<!--            shadow="hover"-->
<!--            style="margin-bottom: 10px; cursor: pointer"-->
<!--            @click.native="paymentMethod = 'alipay'"-->
<!--        >-->
<!--          <div style="display: flex; align-items: center">-->
<!--            <el-radio label="alipay" style="margin-right: 15px" />-->
<!--            <img-->
<!--                src="../../assets/icons/支付宝支付.svg"-->
<!--                style="width: 30px; height: 30px; margin-right: 10px"-->
<!--            />-->
<!--            <span>支付宝支付</span>-->
<!--          </div>-->
<!--        </el-card>-->
<!--        <el-card-->
<!--            shadow="hover"-->
<!--            style="margin-bottom: 10px; cursor: pointer"-->
<!--            @click.native="paymentMethod = 'wechat'"-->
<!--        >-->
<!--          <div style="display: flex; align-items: center">-->
<!--            <el-radio label="wechat" style="margin-right: 15px" />-->
<!--            <img-->
<!--                src="../../assets/icons/微信支付.svg"-->
<!--                style="width: 30px; height: 30px; margin-right: 10px"-->
<!--            />-->
<!--            <span>微信支付</span>-->
<!--          </div>-->
<!--        </el-card>-->
<!--      </el-radio-group>-->
<!--    </div>-->

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button @click="payLater">稍后支付</el-button>
      <el-button
          v-if="orderData.payStatus === 0"
          type="primary"
          @click="handlePayment"
          :loading="paying"
      >
        立即支付
      </el-button>
      <el-button
          v-else
          type="success"
          @click="viewOrderDetail"
      >
        查看订单详情
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from "@/utils/request";

const router = useRouter()

const props = defineProps({
  orderData: {
    type: Object,
    required: true  },
  visible: {
    type: Boolean,
    required: true
  }
})
console.log("组件 visable is ", props.visible)
const emit = defineEmits(['update:visible', 'payment-success'])

// 支付方式
const paymentMethod = ref('alipay')
// 支付中状态
const paying = ref(false)

// 倒计时
const countdown = ref('15:00')
let timer: number | null = null
const remainingTime = ref(900) // 15分钟 = 900秒

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未支付',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取支付状态文本
const getPayStatusText = (status: number) => {
  return status === 1 ? '已支付' : '未支付'
}

// 计算倒计时显示
const updateCountdown = () => {
  const minutes = Math.floor(remainingTime.value / 60)
  const seconds = remainingTime.value % 60
  countdown.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 开始倒计时
const startCountdown = () => {
  if (timer) clearInterval(timer)
  remainingTime.value = 900  //15min
  updateCountdown()

  timer = setInterval(() => {
    remainingTime.value--
    updateCountdown()

    if (remainingTime.value <= 0) {
      clearInterval(timer as number)
      ElMessage.warning('支付超时，订单已自动取消')
      handleClose()
    }
  }, 1000)
}

// 关闭对话框
const handleClose = () => {
  if (timer) clearInterval(timer)
  emit('update:visible', false)
}
const payLater=()=>{
  if (timer) clearInterval(timer)
  ElMessage.info('订单有效时间为15分钟 请稍后前往个人中心/我的订单支付')
  emit('update:visible', false)
}

// 查看订单详情
const viewOrderDetail = () => {
  router.push(`/order/detail/${props.orderData.id}`)
  handleClose()
}

// 处理支付
const handlePayment = async () => {
  paying.value = true
  try {
    console.log("订单数据 is ",props.orderData)
    let formData=new FormData();
    formData.append("id",props.orderData.id)
    const res= await  request.post("/api/commodityOrder/pay",formData)
    console.log("支付订单数据 is ",res)
    console.log("支付订单数据 is ",res.data)
    //@ts-ignore
    if (res.code === 200) {
      ElMessage.success('支付成功')
      //@ts-ignore
      emit('payment-success', res.data)
    } else {
      //@ts-ignore
      ElMessage.error(res.message || '支付失败')
    }
  } catch (error) {
    ElMessage.error('支付失败，请重试')
  } finally {
    paying.value = false
  }
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    startCountdown()
  } else if (timer) {
    clearInterval(timer)
    timer = null
  }
})

// 监听orderData变化，如果已经支付则不显示支付方式
watch(() => props.orderData.payStatus, (newVal) => {
  if (newVal === 1) {
    if (timer) clearInterval(timer)
  }
})

onMounted(() => {
  if (props.visible) {
    startCountdown()
  }
})
</script>

<style scoped>
.el-card {
  transition: all 0.3s;
}
.el-card:hover {
  border-color: #409eff;
}
</style>
